﻿@page "/"
@inject HttpClient Http

<PageTitle>Blazing Trails</PageTitle>

@if (_trails == null)
{
    <p>Loading trails...</p>
}
else
{
    <TrailDetails Trail="_selectedTrail" />

    <TrailSearch />

    <div class="grid">
        @foreach (var trail in _trails)
        {
            <TrailCard Trail="trail" OnSelected="HandleTrailSelected" />
        }
    </div>
}

@code {
    private IEnumerable<Trail>? _trails;
    private Trail? _selectedTrail;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _trails = await Http.GetFromJsonAsync<IEnumerable<Trail>>("trails/trail-data.json");
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"There was a problem loading trail data: {ex.Message}");
        }
    }

    private void HandleTrailSelected(Trail trail) 
        => _selectedTrail = trail;
}